package cn.itcast.music.ui.listen;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import cn.itcast.music.R;
import cn.itcast.music.databinding.ActivityListenBinding;
import cn.itcast.music.entity.Music;
import cn.itcast.music.service.EmptyServiceConnection;
import cn.itcast.music.service.MusicPlayingService;
import cn.itcast.music.service.MusicPlayingService.MusicPlayingBinder;
import cn.itcast.music.util.DateTimeUtil;
import cn.itcast.music.util.MusicUtil;
import java.util.Timer;
import java.util.TimerTask;

public class ListenActivity extends AppCompatActivity {

    private static final String LOG_TAG = "App-listenActivity";

    private ActivityListenBinding binding;

    private MusicPlayingService musicPlayingService;

    private final Timer timer = new Timer();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityListenBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        int position = getIntent().getIntExtra("position", -1);
        if (position == -1) {
            Log.e(LOG_TAG, "启动者必须提供需播放音乐的位置！");
            finish();
        } else {
            doAfterBindPlayingService(position, () -> {
                // 保证在服务连接后再获取服务中的音乐播放信息，更新 UI
                musicPlayingService.play(position);
                initViewData();
                initViewAction();
            });
        }
    }

    private void doAfterBindPlayingService(int position,
            Runnable runAfterBinding) {
        Intent intent = new Intent(this, MusicPlayingService.class);
        intent.putExtra("position", position);
        bindService(intent, new EmptyServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name,
                    IBinder service) {
                musicPlayingService = ((MusicPlayingBinder) service).getService();
                runAfterBinding.run();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                musicPlayingService = null;
            }
        }, BIND_AUTO_CREATE);
    }

    @SuppressLint("SetTextI18n")
    private void initViewData() {
        Music music = musicPlayingService.currentMusic();
        binding.ivAlbum.setImageBitmap(
                MusicUtil.getAlbumBitmap(this, music.getPath()));
        binding.tvTitle.setText(music.getTitle());
        binding.tvArtist.setText(music.getArtist());
        binding.sb.setProgress(musicPlayingService.currentProgress());
        binding.tvProgressTime.setText(
                DateTimeUtil.formatTime(musicPlayingService.currentProgress()));
        binding.sb.setMax((int) music.getDuration());
        binding.tvTotalTime.setText(
                DateTimeUtil.formatTime(music.getDuration()));
        if (musicPlayingService.isPlaying()) {
            binding.tvPlayPause.setBackgroundResource(R.drawable.pause);
        } else {
            binding.tvPlayPause.setBackgroundResource(R.drawable.play);
        }
    }

    private void initViewAction() {
        OnClickListener listener = view -> {
            if (view.getId() == R.id.tv_play_pause) {
                musicPlayingService.playOrPause();
                if (musicPlayingService.isPlaying()) {
                    binding.tvPlayPause.setBackgroundResource(R.drawable.pause);
                } else {
                    binding.tvPlayPause.setBackgroundResource(R.drawable.play);
                }
            } else if (view.getId() == R.id.tv_last) {
                musicPlayingService.playLast();
                initViewData();
            } else if (view.getId() == R.id.tv_next) {
                musicPlayingService.playNext();
                initViewData();
            } else if (view.getId() == R.id.tv_exit) {
                finish();
            }
        };
        binding.tvPlayPause.setOnClickListener(listener);
        binding.tvLast.setOnClickListener(listener);
        binding.tvNext.setOnClickListener(listener);
        binding.tvExit.setOnClickListener(listener);

        binding.sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                // Do nothing.
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // Do nothing.
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                musicPlayingService.seekTo(seekBar.getProgress());
            }
        });

        registerForContextMenu(binding.tvMusicList);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    binding.sb.setProgress(
                            musicPlayingService.currentProgress());
                    binding.tvProgressTime.setText(DateTimeUtil.formatTime(
                            musicPlayingService.currentProgress()));
                });
            }
        }, 5, 500);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("播放列表");
        // 动态添加当前歌曲列表进入菜单
        musicPlayingService.addMusicListToMenu(menu);
        // 点击事件
        for (int i = 0; i < menu.size(); i++) {
            menu.getItem(i).setOnMenuItemClickListener(item -> {
                musicPlayingService.play(item.getItemId());
                initViewData();
                return true;
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    @Override
    public void finish() {
        super.finish();
        // 离开 ListenActivity 时展示动画
        overridePendingTransition(R.anim.alpha_in, R.anim.slide_out_top);
    }

}
